package com.ailot.cloud.auth.handler;


import com.ailot.cloud.base.common.dto.Result;
import com.ailot.cloud.base.security.model.JwtUser;
import com.ailot.cloud.base.security.utils.JWTUtil;
import com.ailot.cloud.base.security.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName:JwtAuthenticationSuccessHandler
 * Description: 登录成处理，返回jwt
 */
@Slf4j
@Component
public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {


    private final JwtEncoder jwtEncoder;

    public JwtAuthenticationSuccessHandler(JwtEncoder jwtEncoder) {
        this.jwtEncoder = jwtEncoder;
    }


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //从authentication中获取用户信息
        final JwtUser userDetail = (JwtUser) authentication.getPrincipal();
        log.info("{}:登录成功", userDetail.getUsername());
        String token = jwtEncoder.encode(JWTUtil.authenticationToJwtParameters(userDetail)).getTokenValue();
        ResponseUtil.response(response, Result.success("登录成功", "Bearer "+token));
    }
}
